import axios from 'axios'
import store from '@/store'
import { getTime } from '@/utils/storage'
import router from '@/router'

const request = axios.create({
  baseURL: 'https://slwl-geteway.itheima.net/manager/',
  timeout: 5000
})
const expire = store.state.user.expire
function isTimeOut () {
  const currentTime = Date.now()
  const localTime = getTime()
  return currentTime - localTime > expire * 1000
}
request.interceptors.request.use((config) => {
  const token = store.state.user.token
  if (token) {
    if (isTimeOut()) {
      store.dispatch('user/loginActions')
      router.push('/login')
      return Promise.reject(new Error('token过期'))
    }
    config.headers.Authorization = token
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

request.interceptors.response.use((response) => {
  return response.data
}, (err) => {
  return Promise.reject(err)
})
export default request
